import { Cascader, Input } from 'antd';
import styles from './index.less';
import type { FC } from 'react';
import { useEffect, useMemo, useState } from 'react';

type ValueType = {
  reward?: string[];
  value?: string;
};
interface Props {
  value?: ValueType;
  onChange?: (val: ValueType) => void;
  text?: string;
}

const Index: FC<Props> = ({ text = 'A', value, onChange }) => {
  const options = useMemo(
    () => [
      {
        label: '有奖励',
        value: '有奖励',
        children: [
          {
            label: 'CG券',
            value: 'CG券',
          },
          {
            label: 'RM币',
            value: 'RMB',
          },
        ],
      },
      {
        label: '无奖励',
        value: '无奖励',
      },
    ],
    [],
  );
  const [selVal, setSelVal] = useState<string[] | undefined>();
  const [inpVal, setInpVal] = useState<string>();
  const update = (val: ValueType) => {
    if (onChange) {
      onChange(val);
    } else {
      setSelVal(val.reward);
      setInpVal(val.value);
    }
  };
  const onRewardChange = (val: string[]) => {
    update({
      value: val?.[0] === '无奖励' ? undefined : inpVal,
      reward: val,
    });
  };
  const onInputChange = (evt) => {
    update({
      value: evt.target.value,
      reward: selVal,
    });
  };
  useEffect(() => {
    setSelVal(value?.reward);
    setInpVal(value?.value);
  }, [value]);
  return (
    <div className={styles.flex}>
      <span>{text}</span>
      <div className={styles.content}>
        <Cascader
          getPopupContainer={(node) => node.parentNode}
          dropdownClassName="c-cascader-container"
          options={options}
          value={selVal}
          showArrow
          onChange={onRewardChange as any}
          showCheckedStrategy={'SHOW_PARENT'}
        >
          <span className={styles.select}>
            {selVal?.[0] ? selVal.map((str) => (str === 'RMB' ? 'RM币' : str)).join('/') : '请选择'}
          </span>
        </Cascader>
        {selVal?.[1] ? (
          <Input
            key={selVal?.[1]}
            value={inpVal}
            style={{ fontSize: 12 }}
            onChange={onInputChange}
            placeholder={selVal?.[1] === 'RMB' ? 'RM币' : 'CG券额度'}
            className={styles.input}
            type="number"
            // addonAfter={selVal?.[1] === 'RMB' ? '¥' : undefined}
          />
        ) : (
          <span className={styles.input}>-</span>
        )}
      </div>
    </div>
  );
};
export default Index;
